import lunisolar from "lunisolar";
import { Solar, Lunar, HolidayUtil } from "lunar-javascript";
import {
  findYueJiangByName,
  findYueJiangByValue,
  getCurrentYueJiang,
} from "./yuejiang";
import dayjs from "dayjs";
import { wuShuDun } from "./ganzhiUtils";
import { adjustHours } from "./dateUtils";
console.log(lunisolar().recentSolarTerm(2)[0].name);
// 取得当前日期在哪那个最近的节之后
lunisolar().recentSolarTerm(1); // 取得当前日期在哪那个最近的气之后
lunisolar().recentSolarTerm(2);
const season = lunisolar().getSeason();
const stem1 = lunisolar().char8.year.stem.name;
const stem2 = lunisolar().char8.month.stem.name;
const stem3 = lunisolar().char8.day.stem.name;
const stem4 = lunisolar().char8.hour.stem.name;

const branch1 = lunisolar().char8.year.branch.name;
const branch2 = lunisolar().char8.month.branch.name;
const branch3 = lunisolar().char8.day.branch.name;
const branch4 = lunisolar().char8.hour.branch.name;

const year = [stem1, branch1];
const month = [stem2, branch2];
const day = [stem3, branch3];
const hour = [stem4, branch4];

var d = Lunar.fromDate(new Date(2025, 5, 21, 3));
var prev = d.getPrevJieQi();
console.log("上一节气 = " + prev.getName() + " " + prev.getSolar().toYmdHms());
var next = d.getNextJieQi();
console.log("下一节气 = " + next.getName() + " " + next.getSolar().toYmdHms());

class qikeDateTimeOption {
  constructor() {}
}
const ye = ["子", "丑", "寅", "酉", "戌", "亥"];
const zhou = ["卯", "辰", "巳", "午", "未", "申"];
function getQiKeDateOption(
  slcYueJiang,
  yueJiangType,
  shehaiType,
  guishenType,
  datetime,
  nianming,
  slcHuoshi,
  hourType,
  zhouyeGui
) {
  let date = Lunar.fromDate(datetime);
  let solardDate = Solar.fromDate(datetime);
  let yueJiang = null;
  let nianMing = [];
  let jieQi = date.getPrevJieQi().getName();
  let gongliDatetime = solardDate.toYmdHms();
  let nongliDatetime = date.toString();
  console.log("农历日期: " + date.toFullString());
  if (yueJiangType == "zx") {
    yueJiang = findYueJiangByValue(slcYueJiang);
  } else {
    yueJiang = getCurrentYueJiang(date.getPrevJieQi().getName());
  }
  nianMing.push({
    gender: nianming.gender,
    birth: strArrToNumberDate(nianming.birth),
    name: '卦主',
  });
  let year = date.getYearInGanZhiExact();
  let month = date.getMonthInGanZhiExact();
  let day = date.getDayInGanZhiExact();
  let hour = date.getTimeInGanZhi();
  // if ((hourType = "hs")) {
  //   hour = slcHour;
  // }
  if (zhouyeGui == "auto") {
    if (zhou.includes(hour[1])) {
      zhouyeGui = "zhou";
    } else {
      zhouyeGui = "ye";
    }
  }
  return {
    id: -1,
    ganzhiDatetime: {
      year,
      month,
      day,
      hour,
    },
    season,
    jieQi: jieQi,
    yueJiang: yueJiang,
    gongliDatetime: gongliDatetime,
    nongliDatetime: nongliDatetime,
    nianMing: nianMing,
    zhouyeGui: zhouyeGui,
    guishenType: guishenType,
    shehaiType: shehaiType,
    hourType: hourType,
    yuejiangType: yueJiangType,
    huoShi: wuShuDun(day[0], slcHuoshi),
    cunDang: {
      fenZu: "默认",
      guaZhu: "",
      guaShi: "",
      zhanShi: "",
      duanYu: "",
      fanKui: "",
      tag: [],
    },
  };
}

function strArrToNumberDate(dateArr) {
  // 1. 基础格式校验（数组长度必须为3）
  if (!Array.isArray(dateArr) || dateArr.length !== 3) {
    throw new Error("请传入 [年, 月, 日] 格式的数组");
  }

  // 2. 转换并校验每个元素（必须是可转为数字的字符串）
  const numberDate = dateArr.map((str, index) => {
    const num = Number(str);
    // 校验是否为有效数字（排除 NaN）
    if (isNaN(num)) {
      const part = ["年", "月", "日"][index];
      throw new Error(`日期${part}格式错误：${str} 不是有效数字`);
    }
    return num;
  });

  // 3. 年月日范围校验（可选，根据业务需求）
  const [year, month, day] = numberDate;
  if (year < 1900 || year > 2100) throw new Error("年份需在 1900-2100 之间");
  if (month < 1 || month > 12) throw new Error("月份需在 1-12 之间");
  if (day < 1 || day > 31) throw new Error("日期需在 1-31 之间"); // 简化校验，如需精确可判断月份天数

  return { year, month, day }; // 返回结构化对象，更易使用
}

function nextAndPrevQike(qkdtopt, v) {
  let datetime = adjustHours(
    dayjs(qkdtopt.gongliDatetime, "YYYY-MM-DD HH:mm:ss").toDate(),
    v
  );
  let date = Lunar.fromDate(datetime);
  let solardDate = Solar.fromDate(datetime);
  let jieQi = date.getPrevJieQi().getName();
  let gongliDatetime = solardDate.toYmdHms();
  let nongliDatetime = date.toString();
  let year = date.getYearInGanZhiExact();
  let month = date.getMonthInGanZhiExact();
  let day = date.getDayInGanZhiExact();
  let hour = date.getTimeInGanZhi();
  return {
    id: qkdtopt.id,
    ganzhiDatetime: {
      year,
      month,
      day,
      hour,
    },
    season,
    jieQi: jieQi,
    yueJiang: qkdtopt.yueJiang,
    gongliDatetime: gongliDatetime,
    nongliDateTime: nongliDatetime,
    nianMing: qkdtopt.nianMing,
    zhouyeGui: qkdtopt.zhouyeGui,
    guishenType: qkdtopt.guishenType,
    shehaiType: qkdtopt.shehaiType,
    hourType: qkdtopt.hourType,
    yuejiangType: qkdtopt.yueJiangType,
    huoShi: qkdtopt.huoShi,
    cunDang: {
      fenZu: qkdtopt.cunDang.fenZu,
      guaZhu: qkdtopt.cunDang.guaZhu,
      guaShi: qkdtopt.cunDang.guaShi,
      zhanShi: qkdtopt.cunDang.zhanShi,
      duanYu: qkdtopt.cunDang.duanYu,
      fanKui: qkdtopt.cunDang.fanKui,
      tag: qkdtopt.cunDang.tag
    },
  };
}
function getDateBySj(sj) {
  let date = dayjs(sj, "YYYY-MM-DD HH:mm:ss").toDate()
  return date
}
function getJieQiBySj(sj) {
  let date = dayjs(sj, "YYYY-MM-DD HH:mm:ss").toDate()
  let lunarDate = Lunar.fromDate(date);
  return lunarDate.getPrevJieQi().getName();
}
function getNongliBySj(sj) {
  let date = dayjs(sj, "YYYY-MM-DD HH:mm:ss").toDate()
  let lunarDate = Lunar.fromDate(date);
  return lunarDate.toString();
}
function getYmdHmsByDate(date) {
  let solarDate = Solar.fromDate(date);
  return solarDate.toYmdHms();
}
export { getQiKeDateOption, year,nextAndPrevQike,getDateBySj,getJieQiBySj,getNongliBySj,getYmdHmsByDate,strArrToNumberDate };
export default {
  year,
  month,
  day,
  hour,
};
